import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { InputManager } from '@/core/InputManager';
import { PLAYER_HEIGHT, GRAVITY } from '@/core/constants';
import { CollisionSystem } from './CollisionSystem';
import { WorldManager } from '@/world/WorldManager';
import { BlockInteraction } from './BlockInteraction';
import { Inventory } from './Inventory';
import { BlockType } from '@/blocks/types';
import { PlayerModel } from './PlayerModel';
import { PlayerCombat } from './PlayerCombat';
import { EnderPearl } from '@/items/EnderPearl';
import { Entity } from '@/entities/Entity';
import { getAudioManager } from '@/audio/AudioManager';
import { GameModeManager, GameMode, PlayerCapabilities } from '@/core/GameModeManager';

export class Player {
  private camera: THREE.PerspectiveCamera;
  private inputManager: InputManager;
  private position: Vec3;
  private velocity: Vec3;
  private rotation: { x: number; y: number };
  private isOnGround = false;
  private speed = 5;
  private jumpSpeed = 8; // 增加跳跃高度，能够跳到1层方块上
  private mouseSensitivity = 0.002;
  private friction = 0.8;
  private collisionSystem: CollisionSystem;
  private blockInteraction: BlockInteraction;
  private inventory: Inventory;
  private inventoryUI?: any; // InventoryUI引用
  private onCraftingTableInteract?: () => void;

  // 视角切换相关
  private cameraMode: 'first' | 'third' = 'first';
  private thirdPersonDistance = 5;

  // 方块交互相关
  private isBreaking = false;
  private breakStartTime = 0;
  private breakDuration = 500; // 0.5秒
  private armSwingAnimation = 0;
  private lastRightClickTime = 0;
  private rightClickCooldown = 200; // 200ms冷却时间防止连续放置

  // 玩家模型和状态
  private playerModel?: PlayerModel;
  private health = 20; // 满血20点
  private maxHealth = 20;
  private hunger = 20; // 饥饿值
  private maxHunger = 20;

  // 战斗系统
  private playerCombat: PlayerCombat;
  private entities: Entity[] = [];

  // 末影珍珠系统
  private thrownEnderPearls: EnderPearl[] = [];
  private worldManager: WorldManager;

  // 音效相关
  private footstepTimer = 0;
  private footstepInterval = 0.5; // 脚步声间隔
  private lastJumpTime = 0;

  // 按键状态管理
  private keyStates: Map<string, boolean> = new Map();
  
  // 聊天输入状态
  private isChatInputActive = false;

  // 游戏模式管理
  private gameModeManager?: GameModeManager;
  private capabilities: PlayerCapabilities = {
    canFly: false,
    invulnerable: false,
    infiniteResources: false,
    canInteract: true,
    canBreakBlocks: true,
    canPlaceBlocks: true,
    flySpeed: 0,
    walkSpeed: 1.0
  };
  private isFlying = false;

  // 死亡UI回调
  private onDeathCallback?: (reason: string) => void;

  constructor(camera: THREE.PerspectiveCamera, inputManager: InputManager, worldManager: WorldManager) {
    this.camera = camera;
    this.inputManager = inputManager;
    this.position = { x: 0, y: 45, z: 0 }; // 适应新的世界高度
    this.velocity = { x: 0, y: 0, z: 0 };
    this.rotation = { x: -0.3, y: 0 }; // 向下看30度
    this.collisionSystem = new CollisionSystem(worldManager);
    this.blockInteraction = new BlockInteraction(worldManager, camera, this.collisionSystem);
    this.inventory = new Inventory();

    // 创建玩家模型（用于第三人称视角）
    this.playerModel = new PlayerModel();

    // 初始化战斗系统
    this.playerCombat = new PlayerCombat(camera);

    // 保存世界管理器引用
    this.worldManager = worldManager;

    this.updateCameraPosition();
  }

  public update(): void {
    this.handleMouseLook();
    this.handleMovement();
    this.handleBlockInteraction();
    this.handleCombat();
    this.applyPhysics();
    this.updateCameraPosition();
    this.updatePlayerModel();
    this.updateEnderPearls();

    // 更新战斗系统
    const deltaTime = 1 / 60;
    this.playerCombat.update(deltaTime);
    
    // 监听聊天输入状态
    this.handleChatInputEvents();
  }

  private handleMouseLook(): void {
    if (!this.inputManager.isPointerLockedActive() || this.isChatInputActive) return;

    const mouseDelta = this.inputManager.getMouseDelta();

    if (mouseDelta.x !== 0 || mouseDelta.y !== 0) {
      this.rotation.y -= mouseDelta.x * this.mouseSensitivity;
      this.rotation.x -= mouseDelta.y * this.mouseSensitivity;

      this.rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, this.rotation.x));
    }
  }

  private handleMovement(): void {
    // 如果聊天输入激活，暂停移动控制
    if (this.isChatInputActive) {
      return;
    }
    
    // 获取相机的前进方向（视线方向）
    const cameraDirection = new THREE.Vector3(0, 0, -1);
    cameraDirection.applyQuaternion(this.camera.quaternion);
    cameraDirection.y = 0; // 我们只关心水平方向
    cameraDirection.normalize();

    // 获取相机的右侧方向（垂直于视线方向）
    const cameraRight = new THREE.Vector3(1, 0, 0);
    cameraRight.applyQuaternion(this.camera.quaternion);
    cameraRight.y = 0;
    cameraRight.normalize();

    // 初始化移动向量
    const moveVector = new THREE.Vector3(0, 0, 0);

    // 根据按键添加移动分量
    if (this.inputManager.isKeyPressed('KeyW')) {
      moveVector.add(cameraDirection);
    }
    if (this.inputManager.isKeyPressed('KeyS')) {
      moveVector.sub(cameraDirection);
    }
    if (this.inputManager.isKeyPressed('KeyA')) {
      moveVector.sub(cameraRight);
    }
    if (this.inputManager.isKeyPressed('KeyD')) {
      moveVector.add(cameraRight);
    }

    // 如果有移动输入，则标准化向量并应用速度
    if (moveVector.length() > 0) {
      moveVector.normalize();
      this.velocity.x = moveVector.x * this.speed;
      this.velocity.z = moveVector.z * this.speed;

      // 播放脚步声
      this.playFootstepSound();
    } else {
      // 应用摩擦力
      this.velocity.x *= this.friction;
      this.velocity.z *= this.friction;
    }

    // 跳跃和飞行
    if (this.inputManager.isKeyPressed('Space')) {
      if (this.capabilities.canFly) {
        // 飞行模式
        if (!this.isFlying && this.isOnGround) {
          // 双击空格键开始飞行
          this.isFlying = true;
          this.velocity.y = 0;
        } else if (this.isFlying) {
          // 飞行时上升
          this.velocity.y = this.capabilities.flySpeed * 5;
        }
      } else if (this.isOnGround) {
        // 普通跳跃
        this.velocity.y = this.jumpSpeed;
        this.isOnGround = false;
        this.playJumpSound();
      }
    }

    // 飞行下降（Shift键）
    if (this.capabilities.canFly && this.isFlying && this.inputManager.isKeyPressed('ShiftLeft')) {
      this.velocity.y = -this.capabilities.flySpeed * 5;
    }
  }

  private applyPhysics(): void {
    const deltaTime = 1 / 60;

    // 飞行模式下不应用重力
    if (!this.isFlying) {
      this.velocity.y += GRAVITY * deltaTime;
    } else {
      // 飞行模式下的阻力
      this.velocity.y *= 0.9;
    }

    // 使用碰撞系统检测并处理碰撞
    const newPosition = this.collisionSystem.checkCollision(this.position, this.velocity, deltaTime);
    this.position = newPosition;

    // 检测是否在地面上（飞行时不需要检测）
    if (!this.isFlying) {
      this.isOnGround = this.collisionSystem.isOnGround(this.position);

      // 如果在地面上且速度向下，停止下降
      if (this.isOnGround && this.velocity.y < 0) {
        this.velocity.y = 0;
      }
    } else {
      this.isOnGround = false;
    }
  }

  private updateCameraPosition(): void {
    if (this.cameraMode === 'first') {
      // 第一人称视角
      this.camera.position.set(this.position.x, this.position.y + PLAYER_HEIGHT, this.position.z);
    } else {
      // 第三人称视角
      const yaw = this.rotation.y;
      const pitch = this.rotation.x;

      // 计算第三人称相机位置（在玩家后方）
      const offsetX = Math.sin(yaw) * this.thirdPersonDistance * Math.cos(pitch);
      const offsetZ = Math.cos(yaw) * this.thirdPersonDistance * Math.cos(pitch);
      const offsetY = -Math.sin(pitch) * this.thirdPersonDistance;

      this.camera.position.set(
        this.position.x + offsetX,
        this.position.y + PLAYER_HEIGHT + offsetY,
        this.position.z + offsetZ
      );

      // 让相机看向玩家
      this.camera.lookAt(this.position.x, this.position.y + PLAYER_HEIGHT, this.position.z);
    }

    // 只在第一人称时设置相机旋转
    if (this.cameraMode === 'first') {
      this.camera.rotation.order = 'YXZ';
      this.camera.rotation.y = this.rotation.y;
      this.camera.rotation.x = this.rotation.x;
    }
  }

  private toggleCameraMode(): void {
    this.cameraMode = this.cameraMode === 'first' ? 'third' : 'first';
    console.log(`切换到${this.cameraMode === 'first' ? '第一' : '第三'}人称视角`);
  }

  public getPosition(): Vec3 {
    return { ...this.position };
  }

  public setPosition(position: Vec3): void {
    this.position = { ...position };
    this.updateCameraPosition();
  }

  private handleBlockInteraction(): void {
    // 如果聊天输入激活，暂停方块交互
    if (this.isChatInputActive) {
      return;
    }
    
    const currentTime = Date.now();

    // 左键长按破坏方块
    if (this.inputManager.isMouseButtonPressed(0)) {
      if (!this.isBreaking) {
        this.isBreaking = true;
        this.breakStartTime = currentTime;
        this.armSwingAnimation = 0;
      }

      // 更新手臂挥动动画
      const breakProgress = Math.min((currentTime - this.breakStartTime) / this.breakDuration, 1);
      this.armSwingAnimation = Math.sin(breakProgress * Math.PI * 4) * 0.3; // 挥动动画

      // 0.5秒后破坏方块
      if (currentTime - this.breakStartTime >= this.breakDuration) {
        this.blockInteraction.breakBlock();
        this.isBreaking = false;
        this.armSwingAnimation = 0;
      }
    } else {
      // 松开左键，停止破坏
      if (this.isBreaking) {
        this.isBreaking = false;
        this.armSwingAnimation = 0;
      }
    }

    // 右键单击建造/交互
    if (this.inputManager.isMouseButtonPressed(2)) {
      if (currentTime - this.lastRightClickTime > this.rightClickCooldown) {
        this.lastRightClickTime = currentTime;

        // 首先检查是否点击了可交互的方块
        const interaction = this.blockInteraction.interactWithBlock();
        if (interaction && interaction.blockType === BlockType.CRAFTING_TABLE) {
          // 与工作台交互
          if (this.onCraftingTableInteract) {
            this.onCraftingTableInteract();
          }
        } else {
          // 否则尝试放置方块
          const selectedItem = this.inventory.getSelectedItem();
          if (selectedItem) {
            this.blockInteraction.placeBlock(selectedItem.type, this.position);
          }
        }
      }
    }

    // E键打开背包或工作台（只在按键刚按下时触发）
    const eKeyPressed = this.inputManager.isKeyPressed('KeyE');
    const eKeyWasPressed = this.keyStates.get('KeyE') || false;

    if (eKeyPressed && !eKeyWasPressed) {
      const interaction = this.blockInteraction.interactWithBlock();
      if (interaction && interaction.blockType === BlockType.CRAFTING_TABLE) {
        // 对着工作台按E，打开工作台
        if (this.onCraftingTableInteract) {
          this.onCraftingTableInteract();
        }
      } else {
        // 否则打开背包
        this.openInventory();
      }
    }

    this.keyStates.set('KeyE', eKeyPressed);

    // 快捷栏选择
    for (let i = 0; i < 9; i++) {
      if (this.inputManager.isKeyPressed(`Digit${i + 1}`)) {
        this.inventory.setSelectedSlot(i);
      }
    }

    // T键现在用于聊天系统，由Game类处理

    // 视角切换 F2/F3
    if (this.inputManager.isKeyPressed('F2')) {
      this.toggleCameraMode();
    }
    if (this.inputManager.isKeyPressed('F3')) {
      this.toggleCameraMode();
    }

    // 游戏模式切换快捷键处理
    this.handleGameModeKeys();
  }

  private openInventory(): void {
    if (this.inventoryUI) {
      this.inventoryUI.toggleFullInventory();
    }
  }

  public setInventoryUI(inventoryUI: any): void {
    this.inventoryUI = inventoryUI;
  }

  public addItemWithDrop(blockType: BlockType, count: number = 1): void {
    const result = this.inventory.addItemWithOverflow(blockType, count);

    // 如果有溢出的物品，在玩家位置掉落
    if (result.overflow > 0) {
      this.dropItemAtPlayer(blockType, result.overflow);
    }
  }

  private dropItemAtPlayer(blockType: BlockType, count: number): void {
    // 在玩家位置掉落物品
    const dropPosition = {
      x: this.position.x + (Math.random() - 0.5) * 2, // 随机偏移
      y: this.position.y + PLAYER_HEIGHT / 2,
      z: this.position.z + (Math.random() - 0.5) * 2
    };

    // 使用方块交互系统的物品掉落管理器
    if (this.blockInteraction && (this.blockInteraction as any).itemDropManager) {
      (this.blockInteraction as any).itemDropManager.createItemDrop(
        blockType,
        count,
        dropPosition
      );
    }
  }

  public getInventory(): Inventory {
    return this.inventory;
  }

  public setCraftingTableInteractCallback(callback: () => void): void {
    this.onCraftingTableInteract = callback;
  }

  public setItemDropManager(itemDropManager: any): void {
    this.blockInteraction.setItemDropManager(itemDropManager);
  }

  public setRedstoneManager(redstoneManager: any): void {
    // 将红石管理器连接到方块交互系统
    (this.blockInteraction as any).setRedstoneManager(redstoneManager);
  }

  public setGameModeManager(gameModeManager: GameModeManager): void {
    this.gameModeManager = gameModeManager;

    // 设置模式变更回调
    gameModeManager.setOnModeChangeCallback((mode: GameMode, capabilities: PlayerCapabilities) => {
      this.onGameModeChanged(mode, capabilities);
    });

    // 设置死亡回调
    gameModeManager.setOnPlayerDeathCallback(() => {
      this.onHardcoreDeath();
    });

    // 初始化当前模式的能力
    this.capabilities = gameModeManager.getPlayerCapabilities();
    console.log(`Player capabilities updated for ${gameModeManager.getCurrentMode()} mode`);
  }

  private onGameModeChanged(mode: GameMode, capabilities: PlayerCapabilities): void {
    this.capabilities = capabilities;

    // 根据新模式调整玩家状态
    if (capabilities.invulnerable) {
      this.health = this.maxHealth; // 创造模式恢复满血
    }

    if (capabilities.infiniteResources) {
      // 创造模式：补充物品栏
      this.refillInventoryForCreative();
    }

    // 调整移动速度
    this.speed = 5 * capabilities.walkSpeed;

    console.log(`Game mode changed to ${mode}. New capabilities:`, capabilities);
  }

  private onHardcoreDeath(): void {
    console.log('Hardcore death - player is now in spectator mode');
    // 可以在这里添加特殊的死亡效果或UI提示
  }

  private refillInventoryForCreative(): void {
    // 为创造模式补充基础方块
    const creativeItems = [
      BlockType.STONE, BlockType.GRASS, BlockType.DIRT, BlockType.LOG,
      BlockType.PLANKS, BlockType.GLASS, BlockType.SAND, BlockType.WATER,
      BlockType.LAVA, BlockType.IRON_ORE, BlockType.GOLD_ORE, BlockType.DIAMOND_ORE
    ];

    creativeItems.forEach((blockType, index) => {
      if (index < 36) { // 物品栏槽位限制
        this.inventory.setItem(index, blockType, 64);
      }
    });
  }

  private updatePlayerModel(): void {
    if (this.playerModel) {
      // 更新玩家模型位置和旋转
      this.playerModel.setPosition(this.position);
      this.playerModel.setRotation(this.rotation.y);

      // 更新动画
      const deltaTime = 1 / 60;
      this.playerModel.updateAnimation(deltaTime, this.velocity, this.armSwingAnimation);
    }
  }

  public getPlayerModel(): PlayerModel | undefined {
    return this.playerModel;
  }

  public getHealth(): number {
    return this.health;
  }

  public getMaxHealth(): number {
    return this.maxHealth;
  }

  public getHunger(): number {
    return this.hunger;
  }

  public getMaxHunger(): number {
    return this.maxHunger;
  }

  public takeDamage(amount: number): void {
    // 无敌模式下不受伤害
    if (this.capabilities.invulnerable) {
      return;
    }

    this.health = Math.max(0, this.health - amount);
    console.log(`玩家受到 ${amount} 点伤害，当前血量: ${this.health}/${this.maxHealth}`);

    // 检查是否死亡
    if (this.health <= 0) {
      this.handleDeath();
    }
  }

  private handleDeath(): void {
    console.log('Player died!');

    // 确定死亡原因
    const deathReason = this.getDeathReason();

    // 通知死亡UI显示
    if (this.onDeathCallback) {
      this.onDeathCallback(deathReason);
    }

    // 通知游戏模式管理器处理死亡
    if (this.gameModeManager) {
      this.gameModeManager.handlePlayerDeath();
    }
  }

  private getDeathReason(): string {
    // 简化的死亡原因判断
    if (this.position.y < -10) {
      return 'Fell out of the world';
    } else if (this.health <= 0) {
      return 'Took too much damage';
    } else {
      return 'Unknown cause';
    }
  }

  private respawn(): void {
    // 重生逻辑
    this.health = this.maxHealth;
    this.hunger = this.maxHunger;

    // 重置位置到出生点
    this.setPosition({ x: 0, y: 45, z: 0 });

    console.log('Player respawned!');
  }

  public heal(amount: number): void {
    this.health = Math.min(this.maxHealth, this.health + amount);
    console.log(`玩家恢复 ${amount} 点血量，当前血量: ${this.health}/${this.maxHealth}`);
  }

  public addHunger(amount: number): void {
    this.hunger = Math.min(this.maxHunger, this.hunger + amount);
  }

  public reduceHunger(amount: number): void {
    this.hunger = Math.max(0, this.hunger - amount);
  }

  public getCameraMode(): 'first' | 'third' {
    return this.cameraMode;
  }

  public getArmSwingAnimation(): number {
    return this.armSwingAnimation;
  }

  public isBreakingBlock(): boolean {
    return this.isBreaking;
  }

  private handleCombat(): void {
    // 左键攻击（当不在破坏方块时）
    if (this.inputManager.isMouseButtonPressed(0) && !this.isBreaking) {
      const attackedEntity = this.playerCombat.performAttack(this.entities);
      if (attackedEntity) {
        console.log(`玩家攻击了 ${attackedEntity.getType()}!`);
      }
    }

    // 右键投掷末影珍珠
    if (this.inputManager.isMouseButtonPressed(2)) {
      const selectedItem = this.inventory.getSelectedItem();
      if (selectedItem && selectedItem.type === BlockType.ENDER_PEARL) {
        this.throwEnderPearl();
      }
    }
  }

  private throwEnderPearl(): void {
    // 获取投掷方向
    const direction = new THREE.Vector3();
    this.camera.getWorldDirection(direction);

    // 创建末影珍珠
    const enderPearl = new EnderPearl(
      { x: this.position.x, y: this.position.y + PLAYER_HEIGHT, z: this.position.z },
      direction,
      this.worldManager
    );

    // 设置传送回调
    enderPearl.setTeleportCallback((position: Vec3) => {
      this.setPosition(position);
      // 传送时受到少量伤害
      this.takeDamage(2.5);
    });

    this.thrownEnderPearls.push(enderPearl);

    // 消耗末影珍珠
    this.inventory.removeItem(BlockType.ENDER_PEARL, 1);

    console.log('玩家投掷了末影珍珠!');
  }

  private updateEnderPearls(): void {
    const deltaTime = 1 / 60;

    // 更新所有末影珍珠
    for (let i = this.thrownEnderPearls.length - 1; i >= 0; i--) {
      const pearl = this.thrownEnderPearls[i];

      if (!pearl.update(deltaTime)) {
        // 末影珍珠已经消失或触发传送
        pearl.dispose();
        this.thrownEnderPearls.splice(i, 1);
      }
    }
  }

  public setEntities(entities: Entity[]): void {
    this.entities = entities;
  }

  public getEnderPearls(): EnderPearl[] {
    return this.thrownEnderPearls;
  }

  private playFootstepSound(): void {
    const currentTime = Date.now() / 1000;

    // 只有在地面上移动时才播放脚步声
    if (!this.isOnGround || currentTime - this.footstepTimer < this.footstepInterval) {
      return;
    }

    this.footstepTimer = currentTime;

    const audioManager = getAudioManager();
    const footstepSoundId = this.getFootstepSoundId();

    audioManager.playSound(footstepSoundId, {
      position: this.position,
      volume: 0.3,
      pitch: 0.9 + Math.random() * 0.2 // 随机音调变化
    });
  }

  private playJumpSound(): void {
    const currentTime = Date.now();

    // 防止跳跃音效过于频繁
    if (currentTime - this.lastJumpTime < 300) {
      return;
    }

    this.lastJumpTime = currentTime;

    const audioManager = getAudioManager();
    audioManager.playSound('jump', {
      position: this.position,
      volume: 0.4
    });
  }

  private getFootstepSoundId(): string {
    // 根据玩家脚下的方块类型选择脚步声
    const footPosition = {
      x: Math.floor(this.position.x),
      y: Math.floor(this.position.y - 1),
      z: Math.floor(this.position.z)
    };

    const blockType = this.worldManager.getBlock(footPosition);

    switch (blockType) {
      case BlockType.STONE:
      case BlockType.COBBLESTONE:
      case BlockType.COAL_ORE:
      case BlockType.IRON_ORE:
      case BlockType.GOLD_ORE:
      case BlockType.DIAMOND_ORE:
        return 'footstep_stone';

      case BlockType.DIRT:
      case BlockType.GRASS:
      case BlockType.SAND:
      case BlockType.GRAVEL:
        return 'footstep_dirt';

      default:
        return 'footstep_stone'; // 默认使用石头脚步声
    }
  }

  private handleGameModeKeys(): void {
    // G键打开游戏模式选择界面（只在按键刚按下时触发）
    const gKeyPressed = this.inputManager.isKeyPressed('KeyG');
    const gKeyWasPressed = this.keyStates.get('KeyG') || false;

    if (gKeyPressed && !gKeyWasPressed) {
      // 这里需要通过某种方式访问GameModeUI
      // 我们可以通过回调或者事件系统来实现
      console.log('Game mode selection requested');
      // TODO: 触发游戏模式选择界面
    }

    this.keyStates.set('KeyG', gKeyPressed);

    // 快速切换游戏模式的快捷键
    const f4KeyPressed = this.inputManager.isKeyPressed('F4');
    const f4KeyWasPressed = this.keyStates.get('F4') || false;

    if (f4KeyPressed && !f4KeyWasPressed && this.gameModeManager) {
      // F4快速切换生存和创造模式
      const currentMode = this.gameModeManager.getCurrentMode();
      if (currentMode === GameMode.SURVIVAL) {
        this.gameModeManager.switchMode(GameMode.CREATIVE);
      } else if (currentMode === GameMode.CREATIVE) {
        this.gameModeManager.switchMode(GameMode.SURVIVAL);
      }
    }

    this.keyStates.set('F4', f4KeyPressed);
  }

  public openGameModeUI(): void {
    // 这个方法将被Game类调用来打开游戏模式UI
    console.log('Opening game mode UI');
  }

  public getGameModeManager(): GameModeManager | undefined {
    return this.gameModeManager;
  }

  public getCapabilities(): PlayerCapabilities {
    return { ...this.capabilities };
  }

  public getIsFlying(): boolean {
    return this.isFlying;
  }

  public setFlying(flying: boolean): void {
    this.isFlying = flying;
  }

  public setOnDeathCallback(callback: (reason: string) => void): void {
    this.onDeathCallback = callback;
  }

  private testAudioSystem(): void {
    console.log('Testing audio system...');
    const audioManager = getAudioManager();

    // 测试各种音效
    const testSounds = [
      'block_break_stone',
      'block_place',
      'jump',
      'footstep_stone'
    ];

    testSounds.forEach((soundId, index) => {
      setTimeout(() => {
        console.log(`Testing sound: ${soundId}`);
        audioManager.playSound(soundId, {
          position: this.position,
          volume: 0.5
        });
      }, index * 500); // 每0.5秒播放一个音效
    });

    console.log('Audio test sequence started. Press T to test audio system.');
  }

  private chatInputEventsSetup = false;

  private handleChatInputEvents(): void {
    // 只设置一次事件监听器
    if (this.chatInputEventsSetup) {
      return;
    }

    // 监听聊天输入焦点事件
    document.addEventListener('chatInputFocus', () => {
      this.isChatInputActive = true;
    });

    document.addEventListener('chatInputBlur', () => {
      this.isChatInputActive = false;
    });

    this.chatInputEventsSetup = true;
  }

  public isChatInputFocused(): boolean {
    return this.isChatInputActive;
  }
}